package com.example.orchid.paper;

import android.app.Application;
import android.content.Context;

import com.example.orchid.paper.db.DatabaseHelper;
import com.example.orchid.paper.db.NewsDataSource;
import com.example.orchid.paper.db.NewsFavoriteDataSource;
import com.example.orchid.paper.db.NewsReadDataSource;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * PaperApplication
 * Created by Orchid on 2015-10-12.
 */
public class PaperApplication extends Application {

    private static PaperApplication mApplication;

    private DatabaseHelper mDatabaseHelper;
    private static NewsDataSource mNewsDataSource;
    private static NewsReadDataSource mNewsReadDataSource;
    private static NewsFavoriteDataSource mNewsFavoriteDataSource;

    @Override
    public void onCreate() {
        super.onCreate();

        mApplication = this;

        mDatabaseHelper = DatabaseHelper.getInstance(getApplicationContext());

        mNewsDataSource = new NewsDataSource(mDatabaseHelper);
        mNewsReadDataSource = new NewsReadDataSource(mDatabaseHelper);
        mNewsFavoriteDataSource = new NewsFavoriteDataSource(mDatabaseHelper);

        initImageLoader(getApplicationContext());
    }

    private static void initImageLoader(Context applicationContext) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                applicationContext).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCacheSize(50 * 1024 * 1024)
                        // 50 Mb
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs() // Remove for release app
                .build();
        ImageLoader.getInstance().init(config);
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }


    @Override
    public void onTerminate() {
        super.onTerminate();

        mDatabaseHelper.close();
    }

    public static PaperApplication getInstance() {
        return mApplication;
    }

    public static NewsDataSource getDataSource() {
        return mNewsDataSource;
    }

    public static NewsReadDataSource getNewsReadDataSource() {
        return mNewsReadDataSource;
    }

    public static NewsFavoriteDataSource getNewsFavoriteDataSource() {
        return mNewsFavoriteDataSource;
    }

}
